<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input v-model="qureyParams.keyword" style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" @input="changeValue" />
        <!-- 树形组件 -->
        <el-tree ref="deptTree" node-key="id" :data="depts" :props="defaultProps" default-expand-all highlight-current expand-on-click-node="false" @current-change="selectNode" />
        <!-- current-change	当前选中节点变化时触发的事件 -->

      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="space-between">
          <el-button size="mini" @click="sendMuliMessage">群发通知</el-button>
          <el-row>
            <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
            <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
            <el-button size="mini" @click="exportEmployee">excel导出</el-button>
          </el-row>
        </el-row>
        <!-- 表格组件 -->
        <!-- ref--row-key监听table的选择和全选事件，并且给table一个row-key属性，做唯一标识符 -->
        <el-table
          ref="employeeTable"
          v-loading="loading"
          row-key="id"
          :data="list"
          @select="selectChange"
          @select-all="selectChange"
        >
          <el-table-column type="selection" />
          <el-table-column label="头像" width="80px">
            <template #default="{row}">
              <img v-if="!!row.staffPhoto" class="avator" :src="row.staffPhoto">
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" prop="mobile" sortable />
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">外包</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button type="text" size="mini" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="mini" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm title="确定删除该用户吗" @onConfirm="delEmployee(row.id)">
                <template #reference>
                  <el-button style="margin-left: 10px;" type="text" size="mini">删除</el-button>
                </template>
              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end" style="height: 60px;" align="middle">
          <el-pagination
            layout="prev, pager, next , total"
            :total="total"
            :page-size="qureyParams.pagesize"
            :current-page.sync="qureyParams.page"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </div>
    </div>
    <import-excel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="getEmployeeList" />
    <el-dialog title="分配角色" :visible.sync="showRoleDialog">
      <!-- 放置多选框组 -->
      <el-checkbox-group v-model="roleIds">
        <!-- label表示标识 -->
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>
      <el-row type="flex" justify="center" style="height: 80px;" align="middle">
        <el-button size="mini" type="primary" @click="btnRoleOK">确定</el-button>
        <el-button size="mini" @click="showRoleDialog = false">取消</el-button>
      </el-row>
    </el-dialog>
    <!-- 放置显示消息的弹层 -->
    <el-dialog title="群发通知" :visible.sync="showMultiMessageDialog">
      <div class="selct_users">
        <el-tag
          v-for="item in all_users"
          :key="item.id"
          class="slect-tag-user"
          closable
          @close="delSendUser(item)"
        >@{{ item.username }}</el-tag>
      </div>
      <el-form label-width="80px">
        <el-form-item label="消息等级">
          <el-select v-model="messageForm.type" size="mini">
            <el-option :value="1" label="通知消息" />
            <el-option :value="2" label="提示消息" />
            <el-option :value="3" label="重要消息" />
            <el-option :value="4" label="紧急消息" />
          </el-select>
        </el-form-item>
        <el-form-item label="通知内容">
          <el-input v-model="messageForm.content" type="textarea" :rows="4" placeholder="通知内容的长度在5-100个字符" />
        </el-form-item>
      </el-form>
      <!-- 群发通知 -->
      <template #footer>
        <el-row type="flex" justify="end">
          <el-button size="mini" @click="showMultiMessageDialog = false"> 取消</el-button>
          <el-button type="primary" size="mini" @click="btnSendMultiMessage"> 发送通知</el-button>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { delEmployeeAPI, exportEmployeeAPI, getEmployeeDetail, getDepartMentAPI, getEmployeeListAPI, getEmployeeDetailAPI, getEnableRoleAPI, assignRoleAPI, sendMultiMessageAPI } from '@/api'
import { transListToTreeDate } from '@/utils'
import FileSaver from 'file-saver'
import { ImportExcel } from './components'

export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      // 消息解构
      messageForm: {
        type: 1,
        content: ''
      },
      showMultiMessageDialog: false, // 控制群发消息弹层的显示和隐藏
      selectUsers: {}, // 存储每一页的用户，示例{1:[],2:[],3:[]....}
      currentUserId: null, // 用来记录当前点击的用户id
      showRoleDialog: false, // 用来控制角色弹层的显示
      roleList: [], // 接收角色列表
      roleIds: [], // 用来双向绑定数据的
      showExcelDialog: false, // 控制弹层excel的显示和隐藏
      depts: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      qureyParams: {
        departmentId: null,
        pagesize: 10, // 当前页码数
        page: 1, // 当前页码
        keyword: '' // 模糊检索
      },
      total: 0, // 记录员工的总数
      list: [], // 获取员工数据列表
      loading: false
    }
  },
  computed: {
    all_users() {
      return [...Object.values(this.selectUsers).flat()]// 为什么要进行浅拷贝 想摆脱和之前数据关系
    }
  },
  created() {
    this.getDepartMent()
    this.$route.params.id && this.getEmployeeDetail()
    // !this.$route.params.id ll this.getEmployeeDetail()
    // if (this.$route.params.id) {
    // this.getEmployeeDetail()}
  },
  methods: {
    // 发送消息
    async btnSendMultiMessage() {
      if (!this.all_users.length) {
        return this.$message.warning('发送的用户不能为空')
      }
      if (!this.messageForm.content) {
        return this.$message.warning('消息内容不能为空')
      }

      await sendMultiMessageAPI({
        userIds: this.all_users.map(item => item.id),
        ...this.messageForm
      })
      this.$message.success('群发消息成功')
      this.messageForm = {
        type: 1,
        content: ''
      }
      this.showMultiMessageDialog = false
    },

    // 删除已选中的用户
    delSendUser(item) {
      // 删除selectUser中的数据
      // 页面上取消勾选
      Object.keys(this.selectUsers).forEach(key => {
        const index = this.selectUsers[key].findIndex(row => row.id === item.id)
        if (index > -1) {
          this.selectUsers[key].splice(index, 1) // 删除存储的数据
          this.$refs.employeeTable.toggleRowSelection(item.false) // 页面上取消勾选
        }
      })
    },

    // 发送多个消息
    sendMuliMessage() {
      // 检查是否已经选择了用户 !this.all_users.length
      if (!this.all_users.length) {
        return this.$message.warning('请选择要发送消息的用户')
      }
      this.showMultiMessageDialog = true
    },

    // 当勾选或者触发时勾选
    selectChange(selectRows) {
      // 把当前页面的数据勾选给到selectUser存储起来[]
      // console.log(selectRows)

      this.selectUsers = {
        ...this.selectUsers,
        [this.qureyParams.page]: selectRows
      }
      console.log(this.selectUsers)
    },

    async btnRole(id) {
      this.showRoleDialog = true // 弹出层
      this.roleList = await getEnableRoleAPI() // 获取所有可用角色
      // 记录当前点击的id 因为后边 确定取消要存取给对应的用户
      this.currentUserId = id
      const { roleIds } = await getEmployeeDetail(id)
      this.roleIds = roleIds
    },

    async getDepartMent() {
      this.depts = transListToTreeDate(await getDepartMentAPI(), 0)
      this.qureyParams.departmentId = this.depts[0].id
      // 设置选中节点
      // 树组件渲染是异步的 等到更新完毕
      this.$nextTick(() => {
        // 此时意味着树渲染完毕
        this.$refs.deptTree.setCurrentKey(this.qureyParams.departmentId)
      })
      // 获取员工数据列表信息
      this.getEmployeeList()
    },

    selectNode(node) {
      this.qureyParams.departmentId = node.id
      this.qureyParams.page = 1
      // 重新加载员工列表数据，确保每个节点都能拿到数据
      this.getEmployeeList()
    },

    async getEmployeeList() {
      this.loading = true
      // 解构响应数据中的rows数据
      const { rows, total } = await getEmployeeListAPI(this.qureyParams)
      this.list = rows
      this.total = total
      this.loading = false
    },

    async handleCurrentChange(newpage) {
      this.qureyParams.page = newpage
      await this.getEmployeeList()
      // 把当前页的之前选中的数据回显
      // 固定代码
      this.$refs.employeeTable.store.states.selection = this.selectUsers[this.qureyParams.page] || []
      this.$refs.employeeTable.store.updateSelectionByRowKey() // 重新计算selection
      this.$refs.employeeTable.store.updateAllSelected() // 计算全选
    },

    changeValue() {
      // this.getEmployeeList()
      // 单位时间内只执行最后一次
      // this的实例上赋值了一个timer的属性
      // clearTimeout(this.timer) // 清理上一次的定时器
      // this.timer = setTimeout(() => {
      //   this.queryParams.page = 1
      //   this.getEmployeeList()
      // }, 300)

      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.qureyParams.page = 1
        this.getEmployeeList()
      }, 500)
    },

    async exportEmployee() {
      const result = await exportEmployeeAPI() // 导出所有的员工接口
      // console.log(result)
      FileSaver.saveAs(result, '员工信息表.xlsx') // 下载文件
      this.$message.success('下载完成')
    },

    async delEmployee(id) {
      await delEmployeeAPI(id)
      this.$message.success('删除成功')
      if (this.list.length === 1) this.qureyParams.page--
      this.getEmployeeList()
    },

    async getEmployeeDetail(id) {
      this.depts = await getEmployeeDetailAPI(this.$route.params.id)
    },

    // 点击确定时要调用分配的角色
    async btnRoleOK() {
      await assignRoleAPI({ roleIds: this.roleIds, id: this.currentUserId }) // 给谁分配什么样的角色
      this.$message.success('分配角色成功')
      this.showRoleDialog = false
    }

  }
}
</script>

<style lang="scss" scoped>
.select_users{
  display: flex;
  flex-wrap: wrap;
  .select-tag-user{
    margin: 10px 10px;
  }
}
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
.avator{
  height: 30px;
  width: 30px;
  border-radius: 50% ;
  background:#e6ecec;
}
}

</style>
